package com.gking.processHarvest.service.Module;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gking.processHarvest.common.BaseContext;
import com.gking.processHarvest.common.CustomException;
import com.gking.processHarvest.common.Res;
import com.gking.processHarvest.entity.Harvest;
import com.gking.processHarvest.entity.Module;
import com.gking.processHarvest.entity.Project;
import com.gking.processHarvest.mapper.ModuleMapper;
import com.gking.processHarvest.service.Harvest.HarvestService;
import com.gking.processHarvest.service.Project.ProjectService;
import com.gking.processHarvest.utils.CheckStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@Scope(value = "prototype", proxyMode = ScopedProxyMode.TARGET_CLASS) //三级缓存解决bean循环注入问题
public class ModuleServiceImpl extends ServiceImpl<ModuleMapper, Module> implements ModuleService {

    @Autowired
    private ProjectService projectService;

    @Autowired
    private HarvestService harvestService;


    /**
     * 批量创建模块
     *
     * @param projectId 项目id
     * @param list      模块列表
     * @return s
     */
    @Override
    public Res<String> createModules(String projectId, List<Module> list) {
        if (list.size() <= 0) return Res.error("请将参数补充完整");

        //对传入的模块进行查重
        Set<Module> setMdule = new HashSet<>(list);
        if (setMdule.size() != list.size()) return Res.error("创建项目模块失败，传入的模块存在相同模块名称！");

        //项目如果被删除，则无法修改信息
        CheckStatus<Project> checkStatus = new CheckStatus<>();
        LambdaQueryWrapper<Project> lambdaQueryWrapper = checkStatus.checkIsDelete(
                projectId, Project::getId,
                Project::getMasterId, Project::getIsDelete);
        if (projectService.count(lambdaQueryWrapper) == 0) return Res.error("创建项目模块失败！");

        //遍历每一个新增模块名称，查看该项目是否已经存在此模块
        list.forEach(item -> {

            CheckStatus<Module> checkName = new CheckStatus<>();
            LambdaQueryWrapper<Module> queryWrapper = checkName.checkDuplicateName(
                    item.getName(), Module::getName,
                    Module::getMasterId, Module::getIsDelete);
            queryWrapper.eq(Module::getProjectId, projectId);

            int counts = this.count(queryWrapper);
            if (counts != 0) throw new CustomException("创建失败！该项目模块 " + item.getName() + " 已存在！");

            item.setProjectId(projectId);
        });

        this.saveBatch(list);

        return Res.success("创建模块成功！");
    }


    /**
     * 修改模块信息
     *
     * @param pId  项目id
     * @param mId  模块id
     * @param name 模块名称
     * @param desc 模块描述
     * @return s
     */
    @Override
    @Transactional
    public Res<String> updateInfo(String pId, String mId, String name, String desc) {
        if (pId == null || mId == null || name == null) return Res.error("请将参数补充完整");

        //查看此模块是否已经删除了
        CheckStatus<Module> checkStatus = new CheckStatus<>();
        LambdaQueryWrapper<Module> queryWrapper = checkStatus.checkIsDelete(
                mId, Module::getId,
                Module::getMasterId, Module::getIsDelete);
        if (this.count(queryWrapper) == 0) return Res.error("模块已删除，修改模块失败！");

        //查看此修改的模块名称是否已经存在
        CheckStatus<Module> checkName = new CheckStatus<>();
        LambdaQueryWrapper<Module> wrapper = checkName.checkDuplicateName(
                name, Module::getName,
                Module::getMasterId, Module::getIsDelete);
        wrapper.eq(Module::getProjectId, pId);

        if (this.count(wrapper) > 0) return Res.error("此模块名称已经存在与该项目中！");

        //修改模块信息
        LambdaUpdateWrapper<Module> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(Module::getId, mId);
        lambdaUpdateWrapper.eq(Module::getMasterId, BaseContext.getCurrentId());
        lambdaUpdateWrapper.set(Module::getName, name);
        lambdaUpdateWrapper.set(Module::getDescription, desc);

        this.update(lambdaUpdateWrapper);

        //修改收获中的原模块信息
        LambdaQueryWrapper<Harvest> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Harvest::getMasterId, BaseContext.getCurrentId());
        lambdaQueryWrapper.eq(Harvest::getModuleId, mId);

        //先查询
        List<Harvest> list = harvestService.list(lambdaQueryWrapper);
        //在重新设置信息
        List<Harvest> lists = list.stream().map((item) -> {
            item.setModuleName(name);
            return item;
        }).collect(Collectors.toList());

        harvestService.updateBatchById(lists);

        return Res.success("修改模块信息成功！");
    }


    /**
     * 删除模块
     *
     * @param id 模块id
     * @return s
     */
    @Override
    @Transactional
    public Res<String> delete(String id) {
        if (id == null) return Res.error("请将参数补充完整");

        //查询要删除的模块是否存在
        CheckStatus<Module> checkStatus = new CheckStatus<>();
        LambdaQueryWrapper<Module> queryWrapper = checkStatus.checkIsDelete(
                id, Module::getId,
                Module::getMasterId, Module::getIsDelete);
        if (this.getOne(queryWrapper) == null) return Res.error("要删除的模块不存在！");

        //删除模块
        LambdaUpdateWrapper<Module> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(Module::getId, id);
        wrapper.eq(Module::getMasterId, BaseContext.getCurrentId());
        wrapper.set(Module::getIsDelete, 1);
        wrapper.set(Module::getDeleteTime, LocalDateTime.now());
        this.update(wrapper);

        //将收获中的模块信息删除
        LambdaUpdateWrapper<Harvest> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(Harvest::getMasterId, BaseContext.getCurrentId());
        lambdaUpdateWrapper.eq(Harvest::getModuleId, id);
        lambdaUpdateWrapper.set(Harvest::getModuleId, "");
        lambdaUpdateWrapper.set(Harvest::getModuleName, "");

        harvestService.update(lambdaUpdateWrapper);

        return Res.success("删除模块成功！");
    }


    /**
     * 获取项目模块
     *
     * @param projectId 项目id
     * @return s
     */
    @Override
    public Res<List<Module>> getProjectModules(String projectId) {

        LambdaQueryWrapper<Project> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Project::getId, projectId);
        lambdaQueryWrapper.eq(Project::getMasterId, BaseContext.getCurrentId());
        if (projectService.getOne(lambdaQueryWrapper) == null) return Res.error("你没有权限获取此项目的模块列表！");

        LambdaQueryWrapper<Module> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Module::getMasterId, BaseContext.getCurrentId());
        wrapper.eq(Module::getProjectId, projectId);
        wrapper.eq(Module::getIsDelete, 0);

        List<Module> list = this.list(wrapper);

        return Res.success("获取成功！", list);
    }
}
